<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <style>
        .customization_toolBar {
            border: none;
        }

        .customization_toolBar .toolBar {
            border: none;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            height: 20px;
            margin: 15px 0px 0px 0px;
        }

        .customization_toolBar .toolBar .left_tool_div {
            flex-basis: 85%;
            height: 100%;
            display: flex;
            flex-direction: row;
            align-items: center;
        }

        .left_tool_div > * + * {
            margin-left: 10px;
        }

        .customization_toolBar .toolBar .right_tool_div {
            flex-basis: 15%;
            height: 100%;
            display: flex;
            flex-direction: row;
            justify-content: flex-end;
            align-items: center
        }

        .right_tool_div > * + * {
            margin-left: 10px;
        }

        .text-show-btn {
            border: none;
            font-size: 14px;
            color: #666666;
        }

        .text-show-btn:hover {
            color: #666666;
        }

        .goodsInfoText {
            text-align: left;
            display: flex;
            justify-content: space-between;
            align-items: center;
            white-space: nowrap !important;
            overflow: hidden !important;
            text-overflow: ellipsis !important;
        }

        .laytable-cell-customization {
            text-align: center;
            height: auto !important;
            white-space: normal;
            overflow: visible;
            text-overflow: inherit;
            word-break: break-all;
        }

        .layui-table img {
            max-width: 100%;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" lay-filter="searchForm">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">商品名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="goodsName" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">商品分类</label>
                            <div class="layui-input-inline">
                                <select id="industry" lay-filter="industry"></select>
                            </div>
                            <div class="layui-input-inline">
                                <select id="classes" lay-filter="classes"></select>
                            </div>
                            <div class="layui-input-inline">
                                <select id="pin" lay-filter="pin"></select>
                            </div>
                            <input type="text" name="category" value="" hidden>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">交易时间</label>
                            <div class="layui-input-inline">
                                <input type="text" name="dateRange" id="dateRange" class="layui-input"
                                       placeholder="请选择时间区间">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <fieldset class="customization_toolBar">
            <div class="toolBar">
                <div class="left_tool_div">
                    <div><label id="dateRangeStr" style="font-weight: bold;font-size: 16px"></label></div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn">
                            累计销量<label id="sales_volume" style="color:#ff0004;"></label>件
                        </button>
                    </div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn">
                            销售额<label id="sales_amount" style="color:#ff0004;"></label>
                        </button>
                    </div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn">
                            利润<label id="profit" style="color:#ff0004;"></label>
                        </button>
                    </div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn">
                            盈利率<label id="profit_rate" style="color:#ff0004;"></label>
                        </button>
                    </div>
                    <div>
                        <form class="layui-form">
                            <input type="checkbox" lay-skin="primary" lay-filter="showAll"
                                   title="全部">
                        </form>
                    </div>
                    <div>
                        <form class="layui-form">
                            <input type="checkbox" lay-skin="primary" lay-filter="filterTestOrder"
                                   title="过滤" checked>
                        </form>
                    </div>
                </div>
                <div class="right_tool_div">
                    <div>
                        <button class="layui-btn layui-btn-sm layui-btn-warm orderSalesDataExportExcel">
                            导出
                        </button>
                    </div>
                </div>
            </div>
        </fieldset>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="imgTemp">
            {{# if(d.goodsImage != "" && d.goodsImage != null){ }}
            <img src="{{d.goodsImage.split(',')[0]}}" style="width: 100%;height: 80px;"/>
            {{# } }}
        </script>

        <script type="text/html" id="goodsInfo">
            <div style="margin-left: 10px;margin-top: 10px;margin-bottom: 10px;">
                <div class="goodsInfoText">{{d.goodsName}}</div>
                <div class="goodsInfoText">分类: {{d.goodsCategory}}</div>
                <div class="goodsInfoText">规格: {{d.specification}}</div>
            </div>
        </script>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script>
    let allBtnSelect;
    let myClos = [];
    let filterTestOrder = true;
    layui.use(['form', 'table', 'laydate', 'colorpicker'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            laydate = layui.laydate,
            colorpicker = layui.colorpicker;

        let defDateRange = new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000).toLocaleDateString().split('/').map(function (item) {
            return item.padStart(2, '0');
        }).join('-') + " - " + new Date().toLocaleDateString().split('/').map(function (item) {
            return item.padStart(2, '0');
        }).join('-')

        //执行一个laydate实例
        laydate.render({
            elem: '#dateRange', //指定元素
            max: 0, // 限制最大值为当前日期
            format: 'yyyy-MM-dd', //日期格式
            type: 'date',
            range: true, //开启范围选择
        });


        setDateRangeStr(defDateRange)


        table.render({
            elem: '#currentTableId',
            url: '/trade/sales/good/page/list',
            where: {
                dateRange: getDateRangeJsonStr()
            },
            method: 'GET',
            contentType: 'application/x-www-form-urlencoded',
            parseData: function (res) { //res 即为原始返回的数据
                let data = res.data;
                // 处理数据
                let allGoodsSalesData = data.allGoodsSalesData;
                if (allGoodsSalesData) {
                    const myMap = new Map(Object.entries(allGoodsSalesData));
                    // 更新统计数据
                    myMap.forEach((value, key) => {
                        let id = '#' + key
                        let number;
                        let num = parseFloat(value)
                        if (key === 'sales_volume') {
                            number = Math.floor(num)
                        } else if (key === 'profit_rate') {
                            number = (num * 100).toFixed(2) + '%'
                        } else {
                            number = num.toFixed(2);
                            $(id).text(' ￥' + number);
                            return;
                        }

                        $(id).text(' ' + number);
                    });
                }
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": data.total, //解析数据长度
                    "data": data.list //解析数据列表
                };
            },
            toolbar: false,
            cols: [[
                {
                    field: 'numbering', title: '序号', width: 60, align: 'center', templet: function (d) {
                        return d.LAY_INDEX; //返回序号
                    }
                },
                {
                    field: 'goodsImage',
                    title: '商品图',
                    align: 'center',
                    templet: '#imgTemp',
                    style: 'height:80px;',
                    minWidth: 120
                },
                {field: 'goodsInfo', title: '商品详情', align: 'center', templet: '#goodsInfo', minWidth: 400},
                {
                    field: 'unitPrice', title: '玫丽价', sort: true, align: 'center', templet: function (d) {
                        let num = parseFloat(d.unitPrice)
                        return num.toFixed(2);
                    }
                },
                {
                    field: 'salesVolume', title: '销量', sort: true, align: 'center', templet: function (d) {
                        if (d.refundedQuantity == 0) {
                            return '<div> ' + d.salesVolume + '</div>'
                        } else {
                            return '<div> ' + d.salesVolume + '<label style="color: #00e900">-' + d.refundedQuantity + '</label>' + '</div>'
                        }
                    }
                },
                {field: 'salesAmount', title: '销售额', sort: true, align: 'center'},
                {
                    field: 'cost', title: '成本', sort: true, align: 'center', templet: function (d) {
                        let num = parseFloat(d.cost)
                        return num.toFixed(2);
                    }
                },
                {
                    field: 'profit', title: '利润', sort: true, align: 'center', templet: function (d) {
                        let num = parseFloat(d.profit)
                        return num.toFixed(2);
                    }
                },
                {
                    field: 'profitRate', title: '盈利率', sort: true, align: 'center', templet: function (d) {
                        let num = parseFloat(d.profitRate)
                        return (num * 100).toFixed(2) + '%';
                    }
                },
            ]],
            limits: [10, 20, 30, 40],
            limit: 10,
            page: true,
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            response: { //定义后端 json 格式，详细参见官方文档
                statusName: 'code', //状态字段名称
                statusCode: '200', //状态字段成功值
                msgName: 'msg', //消息字段
                countName: 'count', //总数字段
                dataName: 'data' //数据字段
            },
            done: function (res, curr, count) {
                // 给指定的列加上css样式
                let colsList = this.cols[0];
                myClos = colsList;
                for (let cols of colsList) {
                    if (cols.field === 'goodsImage' || cols.field === 'goodsInfo') {
                        // 添加样式
                        let classStr = ".laytable-cell-1-" + cols.key;
                        $(classStr).addClass('laytable-cell-customization')
                    }
                }
            }
        });

        // 监听表格排序事件
        table.on('sort(currentTableFilter)', function (obj) {
            for (let cols of myClos) {
                if (cols.field === 'goodsImage' || cols.field === 'goodsInfo') {
                    // 添加样式
                    let classStr = ".laytable-cell-1-" + cols.key;
                    $(classStr).addClass('laytable-cell-customization')
                }
            }
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            let dataRangeStr = data.field.dateRange
            data.field.dateRange = getDateRangeJsonStr();
            data.field.filterTestOrder = filterTestOrder;
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: data.field
            }, 'data');
            if (isNotNull(dataRangeStr)) {
                setDateRangeStr(dataRangeStr)
            }
            return false;
        });

        // 是否过滤测试数据
        form.on('checkbox(filterTestOrder)', function (data) {
            if (data.elem.checked) { //判断复选框是否选中
                filterTestOrder = true;
            } else {
                filterTestOrder = false;
            }
            loadingTable();
            return false;
        });

        form.on('checkbox(showAll)', function (data) {
            if (data.elem.checked) { //判断复选框是否选中
                $('#dateRange').val("")
                allBtnSelect = true;
                setDateRangeStr("");
            } else {
                allBtnSelect = false;
                setDateRangeStr(defDateRange)
            }
            loadingTable();
        });


        // 监听导出按钮
        $('.orderSalesDataExportExcel').click(function () {
            // let checkStatus = table.checkStatus('currentTableId');
            let formDate = form.val('searchForm');
            formDate.dateRange = getDateRangeJsonStr();
            formDate.filterTestOrder = filterTestOrder;
            // let data = {
            //     batchIds: [],
            //     batchType: 0,
            //     queryVO: formDate,
            // }
            // if (checkStatus.isAll) {
            //     data.batchType = 1;
            // } else {
            //     let dataList = checkStatus.data;
            //     if (dataList.length > 0) {
            //         let ids = [];
            //         dataList.forEach(function (item) {
            //             ids.push(item.id)
            //         });
            //         data.batchIds = ids;
            //     } else {
            //         data.batchType = 1;
            //     }
            // }
            downloadExcel('/trade/export/goods/sales/data', formDate, '订单销售数据.xlsx', 'POST')
        });

        // 监听表格 行双击事件
        table.on('rowDouble(currentTableFilter)', function (obj) {
            var index = layer.open({
                title: '销售详情',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: './order-info-list.html?goodsNo=' + obj.data.goodsNo,
                end: function () {
                    //关闭弹框后触发
                    reloadTable()
                }
            });
            $(window).on("resize", function () {
                layer.full(index);
            });

        });

    });

    /**
     * 重载表格数据
     */
    function reloadTable() {
        layui.use(['table'], function () {
            let table = layui.table;
            table.reload('currentTableId', {
                url: '/trade/sales/good/page/list'
            });
        })
    }

    // 设置日期显示的文本内容
    function setDateRangeStr(defDateRange) {
        if (!isNotNull(defDateRange)) {
            $("#dateRangeStr").text('全部已售商品');
            return;
        }
        const [startDateStr, endDateStr] = defDateRange.split(' - ');
        const startDate = new Date(startDateStr);
        const endDate = new Date(endDateStr);
        // 格式化开始日期和结束日期
        const formattedStartDate = formatDate(startDate);
        const formattedEndDate = formatDate(endDate);// 组合新的日期字符串
        const newDateStr = `${formattedStartDate} - ${formattedEndDate}`;
        $("#dateRangeStr").text(newDateStr);
    }

    // 获取时间查询区间
    function getDateRangeJsonStr() {
        let dateRangeStr = $('#dateRange').val();
        if (!isNotNull(dateRangeStr)) {
            if (allBtnSelect) {
                // 代表全部被选中了
                return '{}';
            } else {
                // 默认7天内
                dateRangeStr = new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000).toLocaleDateString().split('/').map(function (item) {
                    return item.padStart(2, '0');
                }).join('-') + " - " + new Date().toLocaleDateString().split('/').map(function (item) {
                    return item.padStart(2, '0');
                }).join('-')
            }

        }
        let dataRangeList = dateRangeStr.split(` - `)
        let dataRange = {}
        if (dataRangeList.length === 2) {
            dataRange = {
                'startDate': dataRangeList[0],
                'endDate': dataRangeList[1]
            }
        }
        return JSON.stringify(dataRange)
    }

    /**
     * 重载表格数据
     */
    function loadingTable() {
        layui.use(['form', 'table', 'jquery'], function () {
            var form = layui.form,
                table = layui.table,
                $ = layui.jquery;
            let formDate = form.val('searchForm');
            formDate.dateRange = getDateRangeJsonStr();
            formDate.filterTestOrder = filterTestOrder;
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: formDate
            }, 'data');
        })
    }


    //商品分类下拉框
    layui.use(['form', 'layer', 'jquery'], function () {
        var form = layui.form,
            layer = parent.layer === undefined ? layui.layer : parent.layer,
            $ = layui.jquery;
        let industryText = "";
        let classesText = "";
        let pinText = "";

        //异步加载下拉框数据
        $.get("/goods/category/list/root", {}, function (data) {
            if (data.code != 200) {
                layer.msg(data.msg)
            } else {
                let $html = '<option value="">请选择分类</option>';
                if (data.rows != null) {
                    $.each(data.rows, function (index, item) {
                        $html += "<option value='" + item.id + "'>" + item.category + "</option>";
                    });
                    $("#industry").append($html);
                    //append后必须从新渲染
                    form.render('select');
                }
            }
        });
        //监听行业下拉框
        form.on('select(industry)', function (dataObj) {
            //移除城市下拉框所有选项
            $("#classes").empty();
            let classesHtml = '<option value="">请选择类目</option>';
            $("#classes").html(classesHtml);
            $("#pin").empty();
            let pinHtml = '<option value="">请选择品类</option>';
            $("#pin").html(pinHtml);
            industryText = $("#industry").find("option:selected").text();
            let value = $("#industry").val();
            $('input[name="category"]').val(industryText);
            if (isNotNull(value)) {
                //异步加载下拉框数据
                $.get("/goods/category/list/" + value, function (data) {
                    if (data.code != 200) {
                        layer.msg(data.msg)
                    } else {
                        let $html = "";
                        if (data.rows != null) {
                            $.each(data.rows, function (index, item) {
                                $html += "<option value='" + item.id + "'>" + item.category + "</option>";
                            });
                            $("#classes").append($html);
                            //append后必须从新渲染
                            form.render('select');
                        }
                    }
                });
            } else {
                $('input[name="category"]').val("");
                form.render('select');
            }
        });
        //监听类目下拉框
        form.on('select(classes)', function (dataObj) {
            //移除县区下拉框所有选项
            $("#pin").empty();
            let html = '<option value="">请选择品类</option>';
            $("#pin").html(html);
            classesText = $("#classes").find("option:selected").text();
            let value = $("#classes").val();
            let category = industryText + "-" + classesText;
            $('input[name="category"]').val(category);
            //异步加载下拉框数据
            if (isNotNull(value)) {
                $.get("/goods/category/list/" + value, function (data) {
                    if (data.code != 200) {
                        layer.msg(data.msg)
                    } else {
                        let $html = "";
                        if (data.rows != null) {
                            $.each(data.rows, function (index, item) {
                                $html += "<option value='" + item.id + "'>" + item.category + "</option>";
                            });
                            $("#pin").append($html);
                            //append后必须从新渲染
                            form.render('select');
                        }
                    }
                });
            }
        });

        //监听品类下拉框
        form.on('select(pin)', function (dataObj) {
            pinText = $("#pin").find("option:selected").text();
            let category = industryText + "-" + classesText + "-" + pinText;
            if (!isNotNull($("#pin").val())) {
                category = industryText + "-" + classesText;
            }
            $('input[name="category"]').val(category);
        });

    });
</script>

</body>
</html>